package com.lm.antlr4.service;

import com.lm.antlr4.parser.ExprLexer;
import com.lm.antlr4.parser.ExprParser;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.springframework.stereotype.Service;

@Service
public class ExprService {

    public String parseExpression(String input) {
        CharStream inputStream = CharStreams.fromString(input);
        ExprLexer lexer = new ExprLexer(inputStream);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        ExprParser parser = new ExprParser(tokens);

        ParseTree tree = parser.prog(); // 从起始规则解析
        return tree.toStringTree(parser); // 输出语法树
    }

//    public int evaluate(String expr) {
//        CharStream inputStream = CharStreams.fromString(expr);
//        ExprLexer lexer = new ExprLexer(inputStream);
//        CommonTokenStream tokens = new CommonTokenStream(lexer);
//        ExprParser parser = new ExprParser(tokens);
//        ExprEvalVisitor visitor = new ExprEvalVisitor();
//        return visitor.visit(parser.expr());
//    }
}
